package com.xone.xapp;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public abstract class BasicImageOptActivity extends  BasicActivity {//UserPartActivity BasicActivity
	protected final String TAG = BasicImageOptActivity.class.getSimpleName();
	protected LayoutInflater mInflater;
	/**
	 * 外部父视图
	 * @return
	 */
	public abstract LinearLayout getOuterView();
	
	/**
	 * 获得图片的标记
	 * @return
	 */
	public abstract String getImagesTag();
	
	public abstract String getPostUrl();
	
	public abstract void postFinish(JSONObject result);
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	@Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (resultCode == RESULT_OK) {  
            Uri uri = data.getData();  
            Log.e("uri", uri.toString());
            ContentResolver cr = this.getContentResolver();  
            try {
                //获取视图
                final int index = getOuterView().getChildCount() - 2;
            	//获取图像
                Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));  
                int sWidth = ContextUtils.getScreenWidth(getContext());
                int height = bitmap.getHeight() * sWidth / bitmap.getWidth();
                Bitmap bitmapThumb = ThumbnailUtils.extractThumbnail(bitmap, sWidth, height);
                bitmap.recycle();
                //获取布局
                final View pImageView = mInflater.inflate(R.layout.create_image, null);
                ImageView imageView = (ImageView) pImageView.findViewById(R.id.imageview_select_image);  
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                imageView.getLayoutParams().height = height;
                imageView.setImageBitmap(bitmapThumb);/* 将Bitmap设定到ImageView */
                //添加事件
        		Button rotateImage = (Button)pImageView.findViewById(R.id.rotate_image);
        		rotateImage.setOnClickListener(new OnClickListener() {
        			@Override
        			public void onClick(View v) {
        				ImageView imageView = (ImageView) pImageView.findViewById(R.id.imageview_select_image);
        				ImageViewHolder imageViewHolder = (ImageViewHolder)imageView.getTag();
        				if (null == imageViewHolder) {
        					imageViewHolder = new ImageViewHolder();
        					imageView.buildDrawingCache();
        					Bitmap source = imageView.getDrawingCache();
        					imageViewHolder.setSource(source);
        					imageViewHolder.setHeight(imageView.getHeight());
        					imageViewHolder.setWidth(imageView.getWidth());
        					imageView.setTag(imageViewHolder);
        				}
        				Bitmap bitmap = rotateBitmap(imageViewHolder.getSource(), imageViewHolder.rotate());
        				imageView.getLayoutParams().height = imageViewHolder.step % 2 == 0 ? imageViewHolder.getHeight() : (imageViewHolder.getWidth() * imageViewHolder.getWidth()) / imageViewHolder.getHeight();
        				if (bitmap.getWidth() < imageViewHolder.getWidth()) {
        					imageView.getLayoutParams().width = imageViewHolder.getWidth();
        				}
        				imageView.setImageBitmap(bitmap);
        			}
        		});
        		Button deleteImage = (Button)pImageView.findViewById(R.id.delete_image);
        		deleteImage.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						ImageView imageView = (ImageView) pImageView.findViewById(R.id.imageview_select_image);
        				ImageViewHolder imageViewHolder = (ImageViewHolder)imageView.getTag();
        				getOuterView().removeView(pImageView);
        				if (null != imageViewHolder) {
        					imageViewHolder.getSource().recycle();
        				}
					}
				});
                pImageView.setTag(getImagesTag());
                getOuterView().addView(pImageView, index);
            } catch (FileNotFoundException e) {
                Log.e("Exception", e.getMessage(),e);
            }  
        }  
        super.onActivityResult(requestCode, resultCode, data);  
    }
	
	protected Bitmap rotateBitmap(Bitmap source, float angle) {
	      Matrix matrix = new Matrix();
	      matrix.postRotate(angle);
	      return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
	}
	
	protected class ImageViewHolder {
		protected Bitmap source;
		public int step = 0;
		protected int width;
		protected int height;
		public Float rotate() {
			step ++;
			if (step >= 4) {
				step = 0;
			}
			return 90.0f * step;
		}
		public Bitmap getSource() {
			return source;
		}
		public void setSource(Bitmap source) {
			this.source = source;
		}
		public int getWidth() {
			return width;
		}
		public void setWidth(int width) {
			this.width = width;
		}
		public int getHeight() {
			return height;
		}
		public void setHeight(int height) {
			this.height = height;
		}
	}
	
	public class Base64Task extends AsyncTask<View, Void, String[]> {
		protected List<NameValuePair> list;
		protected Context context;
		public Base64Task(Context context, List<NameValuePair> list) {
			this.context = context;
			this.list = list;
		}
		@Override
		protected String[] doInBackground(View... views) {
			if (isCancelled()) {
				return null;
			}
			String [] results = new String[views.length];
			for (int i = 0; i < views.length; i ++) {
				if (null == views[i]) {
					break;
				}
				ImageView imageView = (ImageView)views[i].findViewById(R.id.imageview_select_image);
				Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
				byte[] byteArray = stream.toByteArray();
				String strBase64 = "data:image/png;base64," + Base64.encodeToString(byteArray, 0);
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				results[i] = strBase64;
			}
			return results;
		}
		@SuppressWarnings("unchecked")
		@Override
		protected void onPostExecute(String [] strBase64) {
			super.onPostExecute(strBase64);
			for (int i = 0; i < strBase64.length; i++) {
				if (null == strBase64[i]) {
					break;
				}
				this.list.add(new BasicNameValuePair("images", strBase64[i]));
			}
			//测试用隐藏progressbar,实际需要放到PostDataTask中去
			new PostDataTask(this.context).execute(this.list);
		}
	}
	
	/**
	 * 提交数据到服务器
	 */
	public class PostDataTask extends AsyncTask<List<NameValuePair>, Integer, JSONObject> {
		protected Context context;
		public PostDataTask(Context context) {
			this.context = context;
		}
		@Override
		protected JSONObject doInBackground(List<NameValuePair>... params) {
			if (isCancelled()) {
				return null;
			}
			Log.i(TAG, "参数个数：" + params[0].size());
			return HttpUtils.httpPost(Constants.APP_URL + getPostUrl(), params[0], new HttpUtils.OnPostSuccessListener<JSONObject>() {
				@Override
				public JSONObject onSuccess(int status, String result) {
					return JSONUtils.getJSONObjectFromString(result);
				}
			}, context);
		}
		@Override
		protected void onPostExecute(JSONObject result) {
			super.onPostExecute(result);
			Log.i(TAG, "Commit success onPostExecute.");
			hideProgress();
			postFinish(result);
		}
	}
	
	protected boolean notPass(String value, String notice) {
		if (StringUtils.isBlank(value)) {
			Toast.makeText(getContext(), notice, Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}
	
	public Map<String, String> checkAndGetValue(Map<String, String> infoMap) {
		Map<String, String> valueMap = new HashMap<String, String>();
		for (Map.Entry<String, String> info : infoMap.entrySet()) {
			EditText editText = (EditText)findViewById(ContextUtils.getResourceId(getContext(), info.getKey(), "id"));
			String value = editText.getText().toString();
			if (StringUtils.isNotBlank(info.getValue()) && notPass(value, info.getValue())) {
				return Collections.emptyMap();
			}
			valueMap.put(info.getKey(), value);
		}
		return valueMap;
	}
	
	public int getImageCount() {
		int images = 0;
		for (int i = 0; i < getOuterView().getChildCount(); i++) {
			View tv = getOuterView().getChildAt(i);
			if (getImagesTag().equals((String)tv.getTag())) {
				images ++;
			}
		}
		return images;
	}
	
}
